<template>
  <div ref="chartRef" style="width: 100%; height: 100%"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';

const chartRef = ref(null);
let chartInstance = null;

const initChart = () => {
  if (!chartRef.value) return;
  
  chartInstance = echarts.init(chartRef.value);
  
  const departments = ['内科', '外科', '儿科', '妇产科', '眼科', '耳鼻喉科', '口腔科', '皮肤科'];
  const data = departments.map(() => Math.floor(Math.random() * 500) + 200).sort((a, b) => a - b);

  const option = {
    title: {
      text: '科室就诊量排名',
      left: 'center',
      textStyle: {
        fontSize: 14,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}<br/>就诊量: {c} 人'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '就诊人数',
      axisLabel: {
        formatter: '{value} 人'
      }
    },
    yAxis: {
      type: 'category',
      data: departments,
      axisLabel: {
        interval: 0,
        rotate: 0
      }
    },
    series: [
      {
        name: '就诊量',
        type: 'bar',
        data: data,
        itemStyle: {
          color: function(params) {
            const colorList = [
              '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae',
              '#749f83', '#ca8622', '#bda29a'
            ];
            return colorList[params.dataIndex];
          }
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c} 人'
        }
      }
    ]
  };

  chartInstance.setOption(option);
};

onMounted(() => {
  initChart();
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
  window.removeEventListener('resize', handleResize);
});

const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};
</script>